import React, { useEffect, useState } from "react";
import { Table, Tag, Typography, Spin } from "antd";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import {
  oneDark,
  oneLight,
} from "react-syntax-highlighter/dist/esm/styles/prism";
import { useTheme } from "../contexts/ThemeContext";

const { Text, Paragraph } = Typography;

// 智能解析和渲染聊天消息内容
const ChatMessage = ({ content, isStreaming = false }) => {
  const [displayContent, setDisplayContent] = useState("");
  const { isDarkMode } = useTheme();

  // 处理流式内容更新
  useEffect(() => {
    if (isStreaming) {
      // 流式内容实时更新
      setDisplayContent(content);
    } else {
      // 非流式内容直接设置
      setDisplayContent(content);
    }
  }, [content, isStreaming]);

  // 检测是否包含Markdown格式
  const detectMarkdownContent = (text) => {
    if (!text) return false;

    // 检测代码块
    if (text.includes("```")) {
      return true;
    }

    // 检测标题（#, ##, ###等开头）
    if (text.match(/^#{1,6}\s+/m)) {
      return true;
    }

    // 检测粗体（**文字** 或 __文字__）
    if (text.match(/\*\*.*?\*\*/) || text.match(/__.*?__/)) {
      return true;
    }

    // 检测斜体（*文字* 或 _文字_）- 更严格的检测
    if (
      text.match(/\s\*[^\*\n]+\*(?:\s|$)/) ||
      text.match(/\s_[^_\n]+_(?:\s|$)/)
    ) {
      return true;
    }

    // 检测有序列表（数字. 开头）
    if (text.match(/^\d+\.\s+/m)) {
      return true;
    }

    // 检测无序列表（- 或 * 或 + 开头）
    if (text.match(/^[-+]\s+/m)) {
      return true;
    }

    // 检测水平线（---, ***, ___）
    if (text.match(/^(-{3,}|\*{3,}|_{3,})$/m)) {
      return true;
    }

    // 检测引用块（> 开头）
    if (text.match(/^>\s+/m)) {
      return true;
    }

    // 检测链接（[文字](url)）
    if (text.match(/\[.*?\]\(.*?\)/)) {
      return true;
    }

    // 检测图片（![文字](url)）
    if (text.match(/!\[.*?\]\(.*?\)/)) {
      return true;
    }

    // 检测HTML标签
    if (text.match(/<[^>]+>/)) {
      return true;
    }

    return false;
  };

  // 检测是否包含表格数据
  const detectTableData = (text) => {
    if (!text) return null;

    // 检测Markdown表格格式：必须有管道符和分隔线
    if (text.includes("|") && text.includes("---")) {
      // 验证是否真的是表格：需要多行，每行都有管道符
      const lines = text.split("\n");
      let tableLinesCount = 0;

      for (let line of lines) {
        if (line.includes("|")) {
          tableLinesCount++;
        }
      }

      // 至少需要3行（表头、分隔线、至少一条数据行）
      if (tableLinesCount >= 3) {
        return parseMarkdownTable(text);
      }
    }

    // 检测简单表格格式 (关键字 | 次数) - 只在其他条件都不满足时使用
    const tableResult = parseSimpleTable(text);
    if (tableResult && tableResult.dataRows.length >= 2) {
      return tableResult;
    }

    return null;
  };

  // 解析Markdown表格
  const parseMarkdownTable = (text) => {
    const lines = text.split("\n").filter((line) => line.trim());
    const tableLines = [];
    let inTable = false;

    for (let line of lines) {
      if (line.includes("|")) {
        tableLines.push(line);
        inTable = true;
      } else if (inTable) {
        break;
      }
    }

    if (tableLines.length < 2) return null;

    // 解析表头
    const headers = tableLines[0]
      .split("|")
      .map((h) => h.trim())
      .filter((h) => h);

    // 跳过分隔线，解析数据行
    const dataRows = tableLines.slice(2).map((line) => {
      const cells = line
        .split("|")
        .map((c) => c.trim())
        .filter((c) => c);
      return cells;
    });

    return { headers, dataRows };
  };

  // 解析简单表格格式 (关键字 | 次数)
  const parseSimpleTable = (text) => {
    const lines = text.split("\n");
    const dataRows = [];

    for (let line of lines) {
      // 匹配多种格式：关键字 | 次数
      const match =
        line.match(/\|\s*(.+?)\s*\|\s*(.+?)\s*\|/) ||
        line.match(/(.+?)\s*\|\s*(\d+)/) ||
        line.match(/(.+?)\s*：\s*(\d+)/);
      if (match && match[1] && match[2]) {
        const keyword = match[1].trim();
        const count = match[2].trim();
        // 过滤掉表头分隔符
        if (!keyword.includes("---") && !count.includes("---")) {
          dataRows.push([keyword, count]);
        }
      }
    }

    if (dataRows.length === 0) return null;

    return {
      headers: ["搜索关键字", "出现次数"],
      dataRows,
    };
  };

  // 检测是否包含统计数据
  const detectStatsData = (text) => {
    // 检测总结性统计信息
    if (
      text.includes("综上所述") ||
      text.includes("总计") ||
      text.includes("统计")
    ) {
      return true;
    }
    return false;
  };

  // 渲染表格
  const renderTable = (tableData) => {
    const columns = tableData.headers.map((header, index) => ({
      title: header,
      dataIndex: `col${index}`,
      key: `col${index}`,
      render: (text, record, rowIndex) => {
        // 特殊处理某些列
        if (header === "出现次数" && !isNaN(text)) {
          return (
            <Tag
              color={
                parseInt(text) > 50
                  ? "red"
                  : parseInt(text) > 10
                  ? "orange"
                  : "blue"
              }>
              {text}
            </Tag>
          );
        }
        if (
          header === "搜索关键字" &&
          (text === "空" || text.includes("空") || text.includes("关键字为空"))
        ) {
          return <Tag color="volcano">{text}</Tag>;
        }
        return text;
      },
    }));

    const dataSource = tableData.dataRows.map((row, index) => {
      const record = { key: index };
      row.forEach((cell, cellIndex) => {
        record[`col${cellIndex}`] = cell;
      });
      return record;
    });

    return (
      <Table
        columns={columns}
        dataSource={dataSource}
        pagination={false}
        size="small"
        style={{
          marginTop: 8,
          marginBottom: 8,
          backgroundColor: "#fafafa",
          borderRadius: "6px",
        }}
        bordered
        scroll={{ x: true }}
      />
    );
  };

  // 渲染Markdown内容
  const renderMarkdown = (content) => {
    return (
      <ReactMarkdown
        remarkPlugins={[remarkGfm]}
        components={{
          // 自定义代码块渲染
          code({ node, inline, className, children, ...props }) {
            const match = /language-(\w+)/.exec(className || "");
            const language = match ? match[1] : "";
            const code = String(children).replace(/\n$/, "");

            // 如果是 Mermaid 图表，显示提示信息
            if (!inline && language === "mermaid") {
              return (
                <div
                  style={{
                    backgroundColor: isDarkMode ? "#1f1f1f" : "#f6f8fa",
                    padding: "16px",
                    borderRadius: "6px",
                    margin: "12px 0",
                    border: `1px solid ${isDarkMode ? "#434343" : "#d0d7de"}`,
                  }}>
                  <div
                    style={{
                      color: isDarkMode ? "#bfbfbf" : "#57606a",
                      fontSize: "12px",
                      marginBottom: "8px",
                      fontWeight: 600,
                    }}>
                    🎨 Mermaid 流程图
                  </div>
                  <pre
                    style={{
                      backgroundColor: isDarkMode ? "#141414" : "#fff",
                      padding: "12px",
                      borderRadius: "4px",
                      overflow: "auto",
                      fontSize: "13px",
                      lineHeight: "1.6",
                      margin: 0,
                      color: isDarkMode ? "#d9d9d9" : "#24292f",
                    }}>
                    <code>{code}</code>
                  </pre>
                  <div
                    style={{
                      color: isDarkMode ? "#8c8c8c" : "#57606a",
                      fontSize: "11px",
                      marginTop: "8px",
                      fontStyle: "italic",
                    }}>
                    💡 提示：可以在支持 Mermaid 的编辑器中查看图表
                  </div>
                </div>
              );
            }

            // 普通代码块
            return !inline && match ? (
              <SyntaxHighlighter
                style={isDarkMode ? oneDark : oneLight}
                language={language}
                PreTag="div"
                customStyle={{
                  margin: "12px 0",
                  borderRadius: "6px",
                  fontSize: "13px",
                  lineHeight: "1.6",
                  backgroundColor: isDarkMode ? "#282c34" : "#fafafa",
                }}
                {...props}>
                {code}
              </SyntaxHighlighter>
            ) : (
              <code
                className={className}
                style={{
                  backgroundColor: isDarkMode ? "#1f1f1f" : "#f5f5f5",
                  padding: "2px 6px",
                  borderRadius: "3px",
                  fontSize: "13px",
                  fontFamily:
                    "'Fira Code', 'Consolas', 'Monaco', 'Courier New', monospace",
                  color: isDarkMode ? "#ff7875" : "#c41d7f",
                }}
                {...props}>
                {children}
              </code>
            );
          },
          // 自定义表格渲染
          table: ({ children }) => (
            <div
              style={{
                overflowX: "auto",
                margin: "16px 0",
                borderRadius: "8px",
                border: `1px solid ${isDarkMode ? "#434343" : "#e8e8e8"}`,
                boxShadow: isDarkMode
                  ? "0 1px 2px rgba(0, 0, 0, 0.3)"
                  : "0 1px 2px rgba(0, 0, 0, 0.05)",
              }}>
              <table
                style={{
                  width: "100%",
                  borderCollapse: "collapse",
                  fontSize: "13px",
                  backgroundColor: isDarkMode ? "#1f1f1f" : "#fff",
                }}>
                {children}
              </table>
            </div>
          ),
          thead: ({ children }) => (
            <thead
              style={{
                backgroundColor: isDarkMode ? "#262626" : "#fafafa",
                borderBottom: `2px solid ${isDarkMode ? "#434343" : "#e8e8e8"}`,
              }}>
              {children}
            </thead>
          ),
          th: ({ children }) => (
            <th
              style={{
                padding: "12px 16px",
                textAlign: "left",
                fontWeight: 600,
                color: isDarkMode ? "#fff" : "#262626",
                fontSize: "13px",
                whiteSpace: "nowrap",
              }}>
              {children}
            </th>
          ),
          td: ({ children }) => (
            <td
              style={{
                padding: "10px 16px",
                borderBottom: `1px solid ${isDarkMode ? "#303030" : "#f0f0f0"}`,
                fontSize: "13px",
                lineHeight: "1.6",
                color: isDarkMode ? "#d9d9d9" : "#262626",
              }}>
              {children}
            </td>
          ),
          tbody: ({ children }) => <tbody>{children}</tbody>,
          tr: ({ children, ...props }) => {
            const isHeader = props.node?.tagName === "tr";
            return (
              <tr
                style={{
                  transition: "background-color 0.2s",
                }}
                onMouseEnter={(e) => {
                  if (!isHeader) {
                    e.currentTarget.style.backgroundColor = isDarkMode
                      ? "#262626"
                      : "#f5f5f5";
                  }
                }}
                onMouseLeave={(e) => {
                  if (!isHeader) {
                    e.currentTarget.style.backgroundColor = "transparent";
                  }
                }}>
                {children}
              </tr>
            );
          },
          // 自定义标题渲染
          h1: ({ children }) => (
            <h2
              style={{
                color: "#1890ff",
                marginBottom: "12px",
                marginTop: "20px",
                fontSize: "20px",
                fontWeight: "600",
                borderBottom: "2px solid #1890ff",
                paddingBottom: "8px",
              }}>
              {children}
            </h2>
          ),
          h2: ({ children }) => (
            <h3
              style={{
                color: "#1890ff",
                marginBottom: "10px",
                marginTop: "16px",
                fontSize: "18px",
                fontWeight: "600",
              }}>
              {children}
            </h3>
          ),
          h3: ({ children }) => (
            <h4
              style={{
                color: isDarkMode ? "#d9d9d9" : "#262626",
                marginBottom: "8px",
                marginTop: "12px",
                fontSize: "16px",
                fontWeight: "600",
              }}>
              {children}
            </h4>
          ),
          h4: ({ children }) => (
            <h5
              style={{
                color: isDarkMode ? "#bfbfbf" : "#595959",
                marginBottom: "6px",
                marginTop: "10px",
                fontSize: "15px",
                fontWeight: "600",
              }}>
              {children}
            </h5>
          ),
          // 自定义段落渲染
          p: ({ children }) => (
            <p
              style={{
                marginBottom: "10px",
                lineHeight: "1.8",
                fontSize: "14px",
                color: isDarkMode ? "#d9d9d9" : "#262626",
              }}>
              {children}
            </p>
          ),
          // 自定义列表渲染
          ul: ({ children }) => (
            <ul
              style={{
                marginBottom: "10px",
                paddingLeft: "24px",
                lineHeight: "1.8",
              }}>
              {children}
            </ul>
          ),
          ol: ({ children }) => (
            <ol
              style={{
                marginBottom: "10px",
                paddingLeft: "24px",
                lineHeight: "1.8",
              }}>
              {children}
            </ol>
          ),
          li: ({ children }) => (
            <li style={{ marginBottom: "4px" }}>{children}</li>
          ),
          // 自定义水平线
          hr: () => (
            <hr
              style={{
                border: "none",
                borderTop: `1px solid ${isDarkMode ? "#434343" : "#e8e8e8"}`,
                margin: "16px 0",
              }}
            />
          ),
          // 自定义引用块渲染
          blockquote: ({ children }) => (
            <blockquote
              style={{
                borderLeft: "4px solid #1890ff",
                backgroundColor: isDarkMode ? "#1f1f1f" : "#f0f5ff",
                paddingLeft: "16px",
                paddingRight: "16px",
                paddingTop: "8px",
                paddingBottom: "8px",
                margin: "12px 0",
                color: isDarkMode ? "#bfbfbf" : "#595959",
                borderRadius: "4px",
              }}>
              {children}
            </blockquote>
          ),
          // 自定义强调文本
          strong: ({ children }) => (
            <strong style={{ color: "#1890ff" }}>{children}</strong>
          ),
          // 自定义链接
          a: ({ children, href }) => (
            <a
              href={href}
              target="_blank"
              rel="noopener noreferrer"
              style={{ color: "#1890ff", textDecoration: "none" }}>
              {children}
            </a>
          ),
        }}
        style={{ fontSize: "14px" }}>
        {content}
      </ReactMarkdown>
    );
  };

  // 渲染格式化的文本
  const renderFormattedText = (text) => {
    const parts = text.split("\n");
    return parts
      .map((part, index) => {
        // 检测标题
        if (
          part.includes("综上所述") ||
          part.includes("总结") ||
          part.includes("统计")
        ) {
          return (
            <Paragraph
              key={index}
              style={{ fontWeight: "bold", color: "#1890ff", marginBottom: 8 }}>
              {part}
            </Paragraph>
          );
        }

        // 检测重点信息
        if (part.includes("关键字") && part.includes("次数")) {
          return (
            <Text
              key={index}
              strong
              style={{ display: "block", marginBottom: 4 }}>
              {part}
            </Text>
          );
        }

        // 普通文本
        if (part.trim()) {
          return (
            <Paragraph key={index} style={{ marginBottom: 4 }}>
              {part}
            </Paragraph>
          );
        }

        return null;
      })
      .filter(Boolean);
  };

  // 主渲染逻辑
  const tableData = detectTableData(displayContent);
  const isStats = detectStatsData(displayContent);
  const isMarkdown = detectMarkdownContent(displayContent);

  // 如果正在流式加载并且内容为空，显示加载指示器
  if (isStreaming && !displayContent.trim()) {
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <Spin size="small" />
        <span style={{ color: "#999", fontSize: "12px" }}>AI正在思考中...</span>
      </div>
    );
  }

  // 优先级：Markdown > 表格 > 统计文本 > 普通文本
  // 如果包含Markdown格式，优先使用Markdown渲染
  if (isMarkdown) {
    return (
      <div>
        {renderMarkdown(displayContent)}
        {isStreaming && (
          <div style={{ marginTop: 8, color: "#999", fontSize: "12px" }}>
            <Spin size="small" style={{ marginRight: 4 }} />
            正在生成中...
          </div>
        )}
      </div>
    );
  }

  // 其次检查表格
  if (tableData) {
    // 分离表格前后的文本
    const lines = displayContent.split("\n");
    const beforeTable = [];
    const afterTable = [];
    let tableFound = false;
    let tableEnded = false;

    for (let line of lines) {
      if (line.includes("|") && !tableEnded) {
        tableFound = true;
      } else if (tableFound && !line.includes("|") && line.trim()) {
        tableEnded = true;
        afterTable.push(line);
      } else if (!tableFound) {
        beforeTable.push(line);
      } else if (tableEnded) {
        afterTable.push(line);
      }
    }

    return (
      <div>
        {beforeTable.length > 0 && renderFormattedText(beforeTable.join("\n"))}
        {renderTable(tableData)}
        {afterTable.length > 0 && renderFormattedText(afterTable.join("\n"))}
        {isStreaming && (
          <div style={{ marginTop: 8, color: "#999", fontSize: "12px" }}>
            <Spin size="small" style={{ marginRight: 4 }} />
            正在生成中...
          </div>
        )}
      </div>
    );
  }

  // 如果包含统计信息但没有表格，也进行格式化
  if (isStats) {
    return (
      <div>
        {renderFormattedText(displayContent)}
        {isStreaming && (
          <div style={{ marginTop: 8, color: "#999", fontSize: "12px" }}>
            <Spin size="small" style={{ marginRight: 4 }} />
            正在生成中...
          </div>
        )}
      </div>
    );
  }

  // 默认渲染
  return (
    <div>
      <div style={{ whiteSpace: "pre-wrap" }}>{displayContent}</div>
      {isStreaming && displayContent.trim() && (
        <div style={{ marginTop: 8, color: "#999", fontSize: "12px" }}>
          <Spin size="small" style={{ marginRight: 4 }} />
          正在生成中...
        </div>
      )}
    </div>
  );
};

export default ChatMessage;
